package com.pri.chat.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.entity.LocalMedia;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BannerBean;
import com.netease.nim.uikit.net.entity.BannerModel;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.FriendsListBean;
import com.netease.nim.uikit.net.entity.MemberBean;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.MainActivity;
import com.pri.chat.R;
import com.pri.chat.activity.OtherPeopleMsgActivity;
import com.pri.chat.activity.ReleaseDTActivity;
import com.pri.chat.adapter.FriendsAdapter;
import com.pri.chat.adapter.LookMemberAdapter;
import com.pri.chat.adapter.MemberAdapter;
import com.pri.chat.model.GzModel;
import com.pri.chat.model.SayModel;
import com.pri.chat.model.UserModel;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.LocationUtil;
import com.pri.chat.utils.StringUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.fragment.FragmentLazy;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/24
 */
public class CityMemberFragment extends FragmentLazy implements BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.OnItemClickListener {

    Unbinder unbinder;
    @BindView(R.id.rec_main)
    RecyclerView recyclerView;
    @BindView(R.id.none)
    ImageView none;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;

    @BindView(R.id.inviteLinear)
    View inviteLinear;
    @BindView(R.id.tv_qkq)
    View tv_qkq;




    private int type;
    private int page = 1;
    private boolean isShowDialog = true;

    public static CityMemberFragment getInstance(int type) {
        CityMemberFragment fragment = new CityMemberFragment();
        fragment.type = type;
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        unbinder.unbind();
    }

    @Override
    protected View initViews(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        View view = layoutInflater.inflate(R.layout.fragment_city_list_layout, viewGroup, false);
        unbinder = ButterKnife.bind(this, view);
        initLayout();
        initSrl();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        initLoc();
        if(!StringUtil.isEmpty(city)){
            inviteLinear.setVisibility(View.GONE);
            refresh();
        }else{
            inviteLinear.setVisibility(View.VISIBLE);
        }
    }

    public void updateDaCall(String memberId, int sfdc) {
        //type 0--打招呼；1--修改其他信息
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId().equals(memberId)) {
                    list.get(i).setSfdc(sfdc);
                    mAdapter.notifyItemChanged(i);
                }
            }
        }
    }

    private String lat, lng, province, city, area;
    private LocationUtil locationUtil;

    private void initLoc() {
        locationUtil = new LocationUtil(mContext);
        locationUtil.dingwei();
        locationUtil.setOnLocChangedListener(new LocationUtil.OnLocChangedListener() {
            @Override
            public void onLocationChanged(AMapLocation loc) {
                Log.i("城市：", loc.getCity());
                province = loc.getProvince();
                if(!StringUtils.isEmpty(loc.getCity()) && !loc.getCity().equals(city)){
                    city = loc.getCity();
                    refresh();
                }
                locationUtil.stopLocation();
                locationUtil.destroyLocation();
            }
        });
    }

    private List<MemberBean> list;
    private MemberAdapter mAdapter;

    private void initLayout() {
        city = SharedHelper.readValueByKeyForString(mContext, "city");
        list = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setNestedScrollingEnabled(false);
        mAdapter = new MemberAdapter(R.layout.item_member, list);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                httpSayHello(position);
            }
        });
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id",mAdapter.getData().get(position).getId());
                RxActivityTool.skipActivity(mContext, OtherPeopleMsgActivity.class,bundle);
            }
        });

        tv_qkq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                getActivity().startActivity(settingsIntent);
            }
        });
    }


    private void httpSayHello(int position) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal("打招呼成功");
            updateDaCall(list.get(position).getId(), 1);
            list.get(position).setSfdc(1);
            sendBroadcastToMain(0, position);
            RxToast.normal(baseBean.getMsg());
        };
        SayModel userModel = new SayModel();
        userModel.setMemberId(SharedHelper.readId(mContext));
        userModel.setOtherMemberId(list.get(position).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().callMember(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    public void sendBroadcastToMain(int type, int postion) {
        MainActivity mainActivity = (MainActivity) getActivity();
        //打招呼
        mainActivity.updateDaCall(list.get(postion).getId(), list.get(postion).getSfdc());
    }


    public void shaixuan(String sex) {
        this.sex = sex;
        if(!isShowDialog){
            refresh();
        }
    }

    private String sex;
    @Override
    protected void initData() {
    }



    private void getData(){
        if (StringUtils.isEmpty(city)) {
        }
        SubscriberOnNextListener<BaseBean<List<MemberBean>>> onNextListener = baseBean -> {
            isShowDialog = false;
            list.addAll(baseBean.getData());
            if (baseBean.getData().size() == 0) {
                RxToast.normal("没有更多数据");
            }
            if (list.size() == 0) {
                none.setVisibility(View.VISIBLE);
                mAdapter.notifyDataSetChanged();
            } else {
                none.setVisibility(View.INVISIBLE);
                mAdapter.notifyDataSetChanged();
            }
        };
        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", page);
        params.put("city", city);
        params.put("sex", sex);
        params.put("memberId", SharedHelper.readId(mContext));
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().getCityMember(new ProgressSubscriber<>(onNextListener, mContext, false), requestBody);
    }

    private void initSrl() {
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh_layout.finishRefresh(1000);
            refresh();
        });
        srlAll.setOnLoadmoreListener(refresh_layout -> {
            refresh_layout.finishLoadmore(1000);
            isShowDialog = false;
            page++;
            getData();
        });
    }

    private void refresh() {
        page = 1;
        isShowDialog = false;
        list.clear();
        mAdapter.notifyDataSetChanged();
        getData();
    }

    private void httpGz(int pos) {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            RxToast.normal(baseBean.getMsg());
            srlAll.autoRefresh();
        };
        GzModel userModel = new GzModel();
        userModel.setGzrId(SharedHelper.readId(mContext));
        userModel.setBgzId(list.get(pos).getId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(userModel));
        HttpMethods.getInstance().saveGuanZhu(new ProgressSubscriber<>(onNextListener, mContext, true), requestBody);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.tv_friends_status:
                httpGz(position);
                break;
        }
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//            NimUIKit.startP2PSession(mContext, mList.get(position).getId());
        Bundle bundle = new Bundle();
        bundle.putString("id", list.get(position).getId());
        RxActivityTool.skipActivity(mContext, OtherPeopleMsgActivity.class, bundle);
    }
}
